import employeesObj from '@/api/constant/employees'
import store from '@/store' // store====this.$store
let clickFn = ''
function fn(dom, obj) {
  let resultItem = ''
  employeesObj.hireType.forEach((item) => {
    if (item.id === obj.value) {
      resultItem = item
    }
  })
  const resultStr = resultItem === '' ? '-' : resultItem.value
  dom.innerText = resultStr
}

const directiveObj = {
  // 指令名:{生命周期}
  imgerror: {
    inserted(dom, obj, vnode) {
      // 只执行一次
      obj.value = obj.value || require('@/assets/common/head.jpg')
      dom.src = dom.src || obj.value
      dom.onerror = () => {
        dom.src = obj.value
      }
    },
    // 更新平时一定要记得带上
    componentUpdated(dom, obj) {
      obj.value = obj.value || require('@/assets/common/head.jpg')
      dom.src = dom.src || obj.value
    },
    unbind(dom) {
      dom.onerror = null
    }
  },
  test: {},
  abcde: {},
  directiveForm: {
    inserted(dom, obj, vnode) {
      fn(dom, obj)
    },
    componentUpdated(dom, obj) {
      fn(dom, obj)
    }
  },
  // 点击dom区域外调用相应事件
  clickOut: {
    inserted(dom, obj, vnode) {
      clickFn = (e) => {
        console.log('clickOut')
        // dom是否包含e.target
        if (!dom.contains(e.target)) {
          obj.value()
        }
      }
      document.addEventListener('click', clickFn)
    },
    unbind(dom, obj, vnode) {
      document.removeEventListener('click', clickFn)
    }
  },
  // 按钮权限控制
  btnControl: {
    inserted(dom, obj) {
      console.log('自定义指令', obj)
      // v-指令名:属性名.修饰符（inlineBlock）="值"
      // 控制dom是否显示，display:none  display:block
      if (!store.state.user.userInfo.roles.points.includes(obj.value)) {
        dom.style.display = 'none'
      } else {
        dom.style.display = obj.modifiers.inlineBlock ? 'inline-block' : 'block'
      }
    },
    componentUpdated(dom, obj) {
      // 控制dom是否显示，display:none  display:block
      if (!store.state.user.userInfo.roles.points.includes(obj.value)) {
        dom.style.display = 'none'
      } else {
        dom.style.display = obj.modifiers.inlineBlock ? 'inline-block' : 'block'
      }
    }
  }
}
export default {
  install(Vue) {
    // Object.keys(directiveObj).forEach((item) => {
    //   Vue.directive(item, directiveObj[item])
    // })
    Object.entries(directiveObj).forEach((item) => {
      Vue.directive(item[0], item[1])
    })
  }
}
